//导入模块
import Request from 'luch-request'
import { BASE_URL, WHITE_LIST } from './constant'
import { useUserStore } from '@/stores/user'
//实例化
const request =new Request({
    baseURL:BASE_URL,
    custom: {
        loading: true
      }
})
//配置请求拦截器
request.interceptors.request.use(
    (config) => {
        if(config.custom?.loading){
            uni.showLoading({ title: '正在加载...', mask: true })
        }
        const store = useUserStore()
        //判断是否有token
        if (store.token&&!WHITE_LIST.includes(config.url as string)) {
          config.header!.Authorization = `Bearer ${store.token}`
        }
      return config
    },
    (error) => {
      return Promise.reject(error)
    }
  )
  // 配置响应拦截器
request.interceptors.response.use(
    (res)=>{
         // 隐藏加载状态提示
    uni.hideLoading()
        if(res.data.code!==10000){
            uni.showToast({
                title: res.data.message,
                icon: 'none',
              })
              return Promise.reject(res.data)
        }
        return res.data?.data
},(error)=>{
    // 隐藏加载状态提示
    uni.hideLoading()
    uni.showToast({
        title:error.data.message,
        icon:'none'
    })
     //判断token失效的情况
     if(error.statusCode === 401){
     //跳转到登录页   
     uni.redirectTo({
      url: `/pages/login/index`
     })
     }
    return Promise.reject(error)
})
// 导出配置好的模网络模块
export { request}